package com.heima.admin.gateway.filter;

import com.heima.common.dtos.Payload;
import com.heima.common.util.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 全局过滤器
 */
@Slf4j
@Component
public class AuthFilter implements GlobalFilter {

    /**
     * 验证用户请求token
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//        获取请求对象
        ServerHttpRequest request = exchange.getRequest();
//        获取响应对象
        ServerHttpResponse response = exchange.getResponse();
//        获取请求路径
        String path = request.getURI().getPath();
//        判断是否登录请求，如果是登录请求，放行
        if(path.contains("/login/in")){
            log.info("登录请求，放行");
//            登录，就放行
            return chain.filter(exchange);
        }
//        从请求头获取token
        String token = request.getHeaders().getFirst("token");
        if(StringUtils.isBlank(token)){
            log.info("token为空，结束");
//            token为空结束
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
//        验证token
        try {
            Payload payload = JwtUtils.getInfoFromToken(token);
            Integer userId = payload.getUserId();
            log.info("userId={}",userId);
//            把userId放入请求，转发
            ServerHttpRequest httpRequest = request.
                    mutate().
                    header("userId", userId.toString()).
                    build();
//            修改exchange中的request
            exchange.mutate().request(httpRequest);
        }catch (Exception e){
//        不通过就结束
            log.info("token异常，结束");
//            token为空结束
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        return chain.filter(exchange);
    }
}
